package com.hongxun.budget.ui.dialog;

import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Spinner;
import android.widget.TextView;

import com.hongxun.budget.R;
import com.hongxun.budget.greendao.BMaterialEntityDao;
import com.hongxun.budget.greendao.DaoSession;
import com.hongxun.budget.ui.adapter.SpinnerAdapter;
import com.hongxun.budget.utils.GreenDaoManager;
import com.hongxun.budget.utils.RecyclerViewUtils;
import com.hongxun.budget.utils.T;
import com.hongxun.greenentity.tk.BMaterialEntity;
import com.hongxun.interfaces.ResponseListener;
import com.jessewu.library.SuperAdapter;
import com.jessewu.library.view.ViewHolder;

import org.greenrobot.greendao.query.QueryBuilder;
import org.greenrobot.greendao.query.WhereCondition;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 选择导线
 */

public class WireDialog extends BaseCenterFragmentDialog {

    @BindView(R.id.spinner)
    Spinner spinner;
    @BindView(R.id.list)
    RecyclerView recyclerView;
    @BindView(R.id.title)
    TextView titleTv;
    ResponseListener listener;
    List<BMaterialEntity> datas = new ArrayList<>();//源数据
    SuperAdapter<BMaterialEntity> superAdapter;
    private Map<Integer, Boolean> checkMap = new HashMap<>();//记录被勾选项，防止错乱
    DaoSession session;
    List<BMaterialEntity> entities;//已经选择了的准入条件
    List<String> noIn;//已选择的对应的准入项ID

    @Override
    protected int getLayoutId() {
        return R.layout.dialog_entrycriteria;
    }

    @Override
    protected void initViews() {
        titleTv.setText("导线");
        noIn = new ArrayList<>();
        for (BMaterialEntity b : entities) {
            noIn.add(b.getGuid());
        }
        session = GreenDaoManager.getInstance().getmDaoSession();
        //获取到所有的导线材料
        QueryBuilder<BMaterialEntity> builder = session.getBMaterialEntityDao().queryBuilder();
        List<BMaterialEntity> materialEntities = builder.where(BMaterialEntityDao.Properties.Guid.notIn(noIn),
                builder.or(BMaterialEntityDao.Properties.MBigtype.eq("导线"), BMaterialEntityDao.Properties.MBigtype.like("电缆"))).list();
        final List<String> spinnerList = new ArrayList<>();
        for (BMaterialEntity e : materialEntities) {//获取子类对应的名称
            if (!spinnerList.contains(e.getMMidtype())) {
                spinnerList.add(e.getMMidtype());
            }
        }
        spinner.setAdapter(new SpinnerAdapter<String>(getActivity(), spinnerList, spinner));
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                checkMap.clear();
                String midType = spinnerList.get(position);//获取到对应的KEY
                getData(midType);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        recyclerView.setLayoutManager(RecyclerViewUtils.getLinearLayoutManagerForVertical(getActivity()));
        recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
        recyclerView.setAdapter(superAdapter = new SuperAdapter<BMaterialEntity>(R.layout.content_dialog_checklist) {
            @Override
            public void bindView(ViewHolder viewHolder, final BMaterialEntity t, final int i) {
                TextView textView = viewHolder.getView(R.id.content);
                String mName = t.getMName();
//                if (mName.contains("，")) {
////                    String[] split = mName.split("，");
////                    if (split.length == 2) {
////                        if (split[0].equals(t.getMMidtype())) {
////                            mName = split[1];
////                        }
////                    }
////                }
                textView.setText(mName);
                CheckBox checkBox = viewHolder.getView(R.id.checkBox);
                checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                        if (b == true) checkMap.put(i, true);
                        else checkMap.remove(i);

                    }
                });
                if (checkMap != null && checkMap.containsKey(i)) {
                    checkBox.setChecked(true);
                } else {
                    checkBox.setChecked(false);
                }
            }
        });
        superAdapter.setData(datas);
        if (spinnerList.size() > 0)
            getData(spinnerList.get(0));
        else T.showLong(context, "未获取相关数据信息，请联系管理员添加");
    }

    //按展示名称排序
    private void getData(String midType) {
        QueryBuilder<BMaterialEntity> builder = session.getBMaterialEntityDao().queryBuilder();
        WhereCondition condition1 = BMaterialEntityDao.Properties.Guid.notIn(noIn);
        WhereCondition condition2 = BMaterialEntityDao.Properties.MMidtype.eq(midType);
        WhereCondition condition3 = BMaterialEntityDao.Properties.MBigtype.eq("导线");
        WhereCondition condition4 = BMaterialEntityDao.Properties.MBigtype.like("电缆");
        List<BMaterialEntity> materialEntities = builder.orderAsc(BMaterialEntityDao.Properties.MName)
                .where(condition1, condition2, builder.or(condition3, condition4))
                .list();
        datas.clear();
        datas.addAll(materialEntities);
        superAdapter.notifyDataSetChanged();
    }

    public WireDialog setEntities(List<BMaterialEntity> entities) {
        this.entities = entities;
        return this;
    }

    public WireDialog setListener(ResponseListener listener) {
        this.listener = listener;
        return this;
    }

    @OnClick(R.id.cancel)
    public void onViewClicked() {
        List<BMaterialEntity> resultDatas = new ArrayList<>();//选择的结果
        for (Integer integer : checkMap.keySet()) {
            resultDatas.add(datas.get(integer));
        }
        listener.response(resultDatas, checkMap);
        dismiss();
    }

}
